<script lang="ts">
	import Tooltip, { Wrapper } from '@smui/tooltip';
	import IconButton, { Icon } from '@smui/button';
	import UserStatistics from './_com/UserStatistics.svelte';
	import AddressList from './_com/AddressList.svelte';
	import { handleReqMounted } from '@/hooks/handleReq';
	import { alova } from '$utils/request';
	import { getValue } from '$utils/get';
	import AddressEdit from './_com/AddressEdit.svelte';
	import { createDialog } from '$components/basic/dialog/dialog';
	import { createMessage } from '$components/basic/message';
	import { onMount } from 'svelte';
	import { useUserstore } from '@/store';
	import { get } from 'svelte/store';
	import type { AccountInfo } from '@/store/modules/user';
	import PwdEdit from './_com/PwdEdit.svelte';
	import SettingEdit from './_com/SettingEdit.svelte';
	import { isImgUrl } from '$utils/lazy';
	import _loadingJPG from '$lib/empty/loading-img.svg';
	import _404JPG from '$lib/empty/nopic.png';

	let userInfo: Member.UserProfile | null = null;
	let avatar = _loadingJPG;
	const handle = (res) => {
		userInfo = res.data as Member.UserProfile;
		const userStore = useUserstore();
		userStore.setAccount(userInfo);
	};
	const params = {};
	const { loading, reqInfo } = handleReqMounted('/member/detail', {
		type: 'post',
		params,
		handle,
		isInit: false
	});

	const infoMap = [
		{ icon: 'account_circle', span: 12, label: 'UserName', value: 'memberData.username' },
		{ icon: 'call', span: 12, label: 'Telephone', value: 'businessData.tel' },
		// { span: 8, label: 'Country Code', value: 'memberData.country' },
		//{ icon: 'bar_chart', span: 8, label: 'Level', value: 'memberData.level' },
		//{ icon: 'bar_chart', span: 8, label: 'OpenID', value: 'memberData.openid' },
		//{ icon: 'bar_chart', span: 8, label: 'Client Type', value: 'memberData.clienType' },
		{ icon: 'star', span: 8, label: 'Client', value: 'memberData.clientTypeTxt' },
		{ icon: 'bar_chart', span: 8, label: 'Level', value: 'memberData.levelTxt' },
		{ icon: 'flag_2', span: 8, label: 'Country', value: 'memberData.countryName' },
		{ icon: 'location_on', span: 8, label: 'Last IP', value: 'memberData.lastIp' },
		{ icon: 'schedule', span: 8, label: 'Created', value: 'memberData.created_at' },
		//{ icon: 'bar_chart', span: 8, label: 'Allow Note', value: 'memberData.allowNote' },
		{ icon: 'store', span: 8, label: 'Company', value: 'businessData.company' },
		{ icon: 'bar_chart', span: 8, label: 'Tax', value: 'businessData.tax' },
		{ icon: 'id_card', span: 8, label: 'Contact', value: 'businessData.name' },
		{ icon: 'work', span: 8, label: 'Job', value: 'businessData.job' },
		{
			icon: 'update',
			span: 24,
			label: 'Last Login Time',
			value: 'memberData.lastLoginTime'
		}
	];

	const getHandledValue = (obj, key, defaultVal) => {
		return (getValue(obj, key, defaultVal) as string).slice(0, -10);
	};

	let addressEditRef: any = null;
	const openEdit = ({ detail: item }: CustomEvent) => {
		console.log(addressEditRef);
		addressEditRef?.init(item.id ? 'Edit Address' : 'Add Address', item);
	};
	const deleteAddressById = (id) => alova.Post('/member-address/delete', { id });
	const deleteItem = ({ detail: item }: CustomEvent) => {
		createDialog(
			'tip',
			'confirm `Delete` this address?',
			async () => {
				await deleteAddressById(item.id);
				createMessage({ type: 'success', message: 'Address deleted', duration: 2000 });
				reqInfo(true);
			},
			'warning',
			true
		);
	};

	let pwdEditRef: any = null;
	const openPwdEdit = () => pwdEditRef?.init('Change Password');

	let settingEditRef: any = null;
	const openSettingEdit = () => settingEditRef?.init('Setting');

	onMount(async () => {
		const userStore = useUserstore();
		if (userStore.initAccountData(() => reqInfo(true))) return;
		userInfo = get(userStore.account).data as unknown as Member.UserProfile;
		const url = getValue(get(userStore.userInfo) as IObject, 'member_info.avatar');
		if (await isImgUrl(avatar)) avatar = url;
		else avatar = _404JPG; // default avatar
	});

	// window.location.reload();
</script>

<div class="user-account flex-cc flex-col p-20px gap-20px">
	<!-- 账户信息 -->
	<div class="userinfo w-1320px max-w-100% min-w-350px flex-cc h-300px bg-blue-100 px-20px">
		<div class="card w-1/4 h-156px flex flex-col items-center justify-center">
			<img src={avatar} class="w-60px h-60px rounded-full" alt="avatar" />
			<div class="user-email color-#555 font-500 font-size-16px line-height-60px">
				service@macnninc.com
			</div>
			<div class="flex-cc gap-10px" style="--mdc-theme-primary: #9ca3af">
				<Wrapper>
					<IconButton class="material-icons border border-solid bg-white" on:click={openPwdEdit}>
						key
					</IconButton>
					<Tooltip>change password</Tooltip>
				</Wrapper>

				<Wrapper>
					<IconButton
						class="material-icons border border-solid bg-white"
						on:click={openSettingEdit}
					>
						settings
					</IconButton>
					<Tooltip>click here to update archives</Tooltip>
				</Wrapper>
			</div>
		</div>

		<div class="card w-3/4 grid grid-cols-24 h-168px gap-1">
			{#each infoMap as item}
				<div
					class="flex flex-row justify-start items-center gap-10px"
					style={`grid-column: span ${item.span}`}
				>
					<i class="material-symbols-outlined color-amber">{item.icon}</i>
					<div class="font-size-16px line-height-28px color-#333">
						<span class="color-gray-5">{item.label}:</span>
						<span>{getValue(userInfo, item.value, '--')} </span>
					</div>
				</div>
			{/each}
		</div>
	</div>

	<!-- 用户订单信息统计 -->
	<UserStatistics state={userInfo ? userInfo?.MemberStats : {}}></UserStatistics>

	<AddressList
		addressList={userInfo?.address_list || []}
		loading={$loading}
		on:openEdit={openEdit}
		on:delete={deleteItem}
	></AddressList>

	<AddressEdit bind:this={addressEditRef} on:fresh={() => reqInfo()} />
	<PwdEdit bind:this={pwdEditRef} on:refresh={() => reqInfo()} />
	<SettingEdit bind:this={settingEditRef} on:refresh={() => reqInfo()} />
</div>
